package club.dmyang.controller;

import club.dmyang.common.enums.RespCodeEnums;
import club.dmyang.common.util.RandomUtil;
import club.dmyang.common.vo.ResposeVo;
import club.dmyang.entity.ArticleWithBLOBs;
import club.dmyang.entity.Category;
import club.dmyang.service.ArticleService;
import club.dmyang.service.CategoryService;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.List;

/**
 * Created by brss on 2018/7/12.
 */
@Controller
public class IndexController {

    /**登录随机背景图数组**/
    private static final String[] PICTURES_LOGIN = {
            "http://img.dmyang.club/FvVp_b-gEUdvtpmbVK9tEb-ONAh3",
            "http://img.dmyang.club/FlnFkUPae-PLflmMnAjknHIZuAds",
            "http://img.dmyang.club/FhztWPOUX6Aal_xfFX9Zv_lFkEUk",
            "http://img.dmyang.club/FhpTGIUlkwzxDzYz6tVcRqPpxYBt",
            "http://img.dmyang.club/FiYykHGihQOx72UalMHJJMMA3JSi"
    };

    @Autowired
    private DefaultKaptcha captchaProducer;

    @Autowired
    private CategoryService categoryService;
    @Autowired
    private ArticleService articleService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 响应默认后台首页
     * @param model
     * @return
     */
    @RequestMapping("/")
    public String test(Model model){
        return "admin/index";
    }
    @RequestMapping("/index")
    public String index(Model model){
        return "admin/index";
    }
    @RequestMapping("/welcome")
    public String welcome(){

        return "admin/welcome";
    }
    @RequestMapping("/article-write")
    public String articleWrite(Model model){
        List<Category> categoryList = categoryService.findAll();
        model.addAttribute("categoryList",categoryList);
        return "admin/article-write";
    }

    @RequestMapping("/article-manage")
    public String articleManage(){
        return "admin/article-manage";
    }

    @RequestMapping("/category-add")
    public String categoryAdd(Model model){
        Category c = categoryService.findOneById(1);
        //model.addAttribute("category",c);
        return "admin/category-add";
    }

    @RequestMapping("/category-manage")
    public String categoryManage(){
        return "admin/category-manage";
    }
    @RequestMapping("/tag-add")
    public String tagMAdd(){
        return "admin/tag-add";
    }
    @RequestMapping("/tag-manage")
    public String tagManage(){
        return "admin/tag-manage";
    }

    @RequestMapping("/friendshiplink-add")
    public String friendshipLinkAdd(){
        return "admin/friendshiplink-add";
    }

    @RequestMapping("/friendshiplink-manage")
    public String friendshipLinkManage(){
        return "admin/friendshiplink-manage";
    }


    @RequestMapping("/notice-add")
    public String noticeAdd(){
        return "admin/notice-add";
    }

    @RequestMapping("/notice-manage")
    public String noticeManage(){
        return "admin/notice-manage";
    }

    @RequestMapping("/carousel-add")
    public String carouselAdd(){
        return "admin/carousel-add";
    }

    @RequestMapping("/carousel-manage")
    public String carouselManage(){
        return "admin/carousel-manage";
    }


    /**
     * 响应浏览器登录页面
     * @param model
     * @return
     */
    @RequestMapping("/loginpage")
    public String loginpage(Model model){
        //设置登录时随机登录背景图片
        model.addAttribute("background", PICTURES_LOGIN[RandomUtil.generateOneNum(0,PICTURES_LOGIN.length-1)]);
        return "common/loginpage";
    }

    /**
     * 登录功能
     * @param username
     * @param password
     * @param vericode
     * @return
     */
    @RequestMapping("/login")
    @ResponseBody
    public ResposeVo login(HttpServletRequest httpServletRequest,
                           HttpServletResponse httpServletResponse,
                           String username,
                           String password,
                           String vericode){

        String captchaId = (String) httpServletRequest.getSession().getAttribute("vrifyCode");
        String parameter = httpServletRequest.getParameter("vericode");
        System.out.println("Session  vrifyCode "+captchaId+" form vrifyCode "+parameter);

        if (!captchaId.equals(parameter)) {
            return new ResposeVo(RespCodeEnums.RESP_CODE_ERROR.getCode(),"错误的验证码");
        }
        //验证码通过，继续登录流程
        // 1.获取Subject
        Subject subject = SecurityUtils.getSubject();
        // 2.封装用户数据
        String md5Passwd = DigestUtils.md5DigestAsHex(password.getBytes());
        UsernamePasswordToken token = new UsernamePasswordToken(username,md5Passwd);
        // 3.执行登录方法
        try{
            //无异常则表示登录成功
            subject.login(token);
            return new ResposeVo(RespCodeEnums.RESP_CODE_SUCC.getCode(),"登录成功");
        }catch (Exception e){
            return new ResposeVo(RespCodeEnums.RESP_CODE_ERROR.getCode(),"登录失败");
        }
    }
    @RequestMapping("/logout")
    public String logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "common/loginpage";
    }

    /**
     * 生成验证码
     * @param httpServletRequest
     * @param httpServletResponse
     * @throws Exception
     */
    @RequestMapping("/vericode")
    public void vericode(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception{
        byte[] captchaChallengeAsJpeg = null;
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        try {
            //生产验证码字符串并保存到session中
            String createText = captchaProducer.createText();
            httpServletRequest.getSession().setAttribute("vrifyCode", createText);
            //使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
            BufferedImage challenge = captchaProducer.createImage(createText);
            ImageIO.write(challenge, "jpg", jpegOutputStream);
        } catch (IllegalArgumentException e) {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        //定义response输出类型为image/jpeg类型，使用response输出流输出图片的byte数组
        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
        httpServletResponse.setHeader("Cache-Control", "no-store");
        httpServletResponse.setHeader("Pragma", "no-cache");
        httpServletResponse.setDateHeader("Expires", 0);
        httpServletResponse.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream =
                httpServletResponse.getOutputStream();
        responseOutputStream.write(captchaChallengeAsJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();
    }

    @RequestMapping("/updatecache")
    @ResponseBody
    public ResposeVo updatecache(){
        try {
            stringRedisTemplate.delete("category_listall");
            stringRedisTemplate.delete("friendshipLink_listAll");
            stringRedisTemplate.delete("tag_listall");
            //stringRedisTemplate.delete("carousel");
        } catch (Exception e) {
            e.printStackTrace();
            return new ResposeVo(RespCodeEnums.RESP_CODE_ERROR.getCode(),"清除缓存失败！");
        }
        return new ResposeVo(RespCodeEnums.RESP_CODE_SUCC.getCode(),"清除缓存成功！");
    }

}
